package com.jspgou.cms.web;

import static com.jspgou.core.web.Constants.MODEL_PERMISSION_KEY;
import static com.jspgou.core.web.Constants.REQUEST_PERMISSION_KEY;

import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.jspgou.core.entity.Website;
import com.jspgou.core.web.SiteUtils;
import com.jspgou.cms.entity.ShopAdmin;
import com.jspgou.cms.manager.ShopAdminMng;
import com.jspgou.cms.service.LoginSvc;
import com.jspgou.cms.web.threadvariable.AdminThread;

/**
 * 商城后台信息拦截器
 * 
 * 登录信息、权限信息
 * 
 * @author liufang
 * 
 */
public class AdminContextInterceptor extends HandlerInterceptorAdapter {
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler)
			throws ServletException {
		Website web = SiteUtils.getWeb(request);
		ShopAdmin admin;
		if (developAdminId != null) {
			// 开发状态
			admin = shopAdminMng.findById(developAdminId);
			// 指定管理员不存在
			if (admin == null) {
				throw new IllegalStateException("developAdminId not found: "
						+ developAdminId);
			}
			Long webId = admin.getWebsite().getId();
			// 指定管理员站点错误
			if (!webId.equals(web.getId())) {
				throw new IllegalStateException("developAdminId's website id="
						+ webId + " not in current website id=" + web.getId());
			}
		} else {
			admin = loginSvc.getAdmin(request, response, web);
		}
		if (admin != null) {
			// 将管理员信息放入ThreadLocal
			AdminThread.set(admin);
			// 权限放入request
			
			
			//*尝试
			Set<String> perms = admin.getPerms();
			//*可能1
			request.setAttribute(REQUEST_PERMISSION_KEY, perms);
			//*将admin放入request中
			CmsUtils.setAdmin(request, admin);
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler, ModelAndView mav)
			throws Exception {
		ShopAdmin admin = AdminThread.get();
		if (admin != null && mav != null && mav.getModelMap() != null
				&& mav.getViewName() != null
				&& !mav.getViewName().startsWith("redirect:")) {
			mav.getModelMap().addAttribute(MODEL_PERMISSION_KEY,
					admin.getPerms());
		}
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		AdminThread.remove();
	}

	@Autowired
	private LoginSvc loginSvc;
	@Autowired
	private ShopAdminMng shopAdminMng;
	private Long developAdminId;

	public void setDevelopAdminId(Long developAdminId) {
		this.developAdminId = developAdminId;
	}

}
